package org.example.Proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.RpcApp;
import org.example.config.RpcConfig;
import org.example.model.RpcRequest;
import org.example.model.RpcResponse;
import org.example.serializer.JacksonSerializer;
import org.example.serializer.Serializer;
import org.example.serializer.SerializerFactory;
import org.example.serializer.SerializerFactorySpi;
import org.example.utils.ConfigUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @description TODO
 * @author sats@jz
 * @date 2024年12月25日 14:29
 */
public class ServiceProxy implements InvocationHandler {

    private static final RpcConfig rpcConfig = RpcApp.getRpcConfig();
//    private static final Serializer serializer = rpcConfig.getSerializer();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        try {
            Serializer serializer = SerializerFactorySpi.getInstance(rpcConfig.getSerializerName());
            String url = "http://" + rpcConfig.getServerHost() + ":" + rpcConfig.getServerPort();
            try (HttpResponse httpResponse = HttpRequest.post(url)
                    .body(serializer.serialize(rpcRequest))
                    .execute()) {
                byte[] result = httpResponse.bodyBytes();
                RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
                return rpcResponse.getData();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
